<template>
  <Nav />
  <van-form @submit="onSubmit" ref="formBox">
    <van-cell-group inset>
      <van-field
        center
        v-model="phone"
        name="phone"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern: regPhone, message: '手机号格式不对哦~' },
        ]"
      >
        <template #button>
          <van-button
            size="small"
            class="form-btn"
            :disabled="!enable"
            @click="sendcode"
          >
            {{ enable ? "发送验证码" : time }}
          </van-button>
        </template></van-field
      >
      <van-field
        v-model="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '验证码为必填项哦~' },
          { pattern: regCode, message: '验证码必须是6位数字哦~' },
        ]"
      />
    </van-cell-group>
    <div style="margin: 16px">
      <van-button
        round
        block
        type="primary"
        native-type="submit"
        @click="submit"
      >
        提交
      </van-button>
    </div>
  </van-form>
</template>

<script>
// 每一次提交数据时要进行表单校验（发送验证码、提交账号密码登录），配合vant表单的require检测、pattern检测。
// 登录成功后修改登录状态，存储用户信息以及token
// 登录完成后使用路由查看from从哪里来的，如果有from的话就登录成功有replace替换url跳转回去，如果没有的话就跳到个人页
import Nav from "@/components/Nav.vue";
import { Toast } from "vant";
import { reactive, toRefs, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useStore } from "@/store/index";
import api from "@/api/index";
export default {
  components: { Nav },
  name: "Login",
  setup() {
    const store = useStore(),
      router = useRouter(),
      route = useRoute();

    let formBox = ref(null);
    let state = reactive({
      phone: "",
      code: "",
      enable: true,
      time: "60s",
    });
    const sendcode = async () => {
      try {
        await formBox.value.validate("phone");
        let { code } = await api.phoneCode(state.phone);
        if (+code !== 0) {
          Toast("小主，当前网络繁忙，请稍后再试哦~");
          return;
        }
        state.enable = false;
        state.time = `5s`;
        let n = 5;
        let timer = setInterval(() => {
          n--;
          if (n === 0) {
            clearInterval(timer);
            state.enable = true;
            return;
          }
          state.time = `${n}s`;
        }, 1000);
      } catch (e) {
        console.log(e);
      }
    };
    const submit = async () => {
      let { code, token } = await api.login(state.phone, state.code);
      if (+code !== 0) {
        Toast("小主，很遗憾，当前登录失败了~");
        formBox.value.resetValidation();
        state.code = "";
        return;
      }

      localStorage.setItem("token", token);
      // 可能要传参
      store.changeIsLoginAsync();
      store.changeInfoAsync();
      Toast("小主真棒，当前登录成功喽~");
      store.changeStoreListAsync();
      let from = route.query.from;
      if (from) {
        router.replace(`/${from}`);
        return;
      }
      router.replace("/person");
    };
    return {
      ...toRefs(state),
      sendcode,
      regPhone: /^1\d{10}$/,
      regCode: /^\d{6}$/,
      formBox,
      submit,
    };
  },
};
</script>

<style lang="less" scoped>
.van-form {
  margin-top: 30px;

  .form-btn {
    width: 78px;
  }
}
</style>
